package 数组算法;

import org.junit.Test;

import java.math.BigDecimal;

public class addTwoNumbers2 {

    /**
     * 暴力的方法： 将遍历 在利用的系统函数加起来
     *
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        String s1 = "";
        while (l1 != null) {
            s1 += String.valueOf(l1.val);
            l1 = l1.next;
        }
        String s2 = "";
        while (l2 != null) {
            s2 += String.valueOf(l2.val);
            l2 = l2.next;
        }
        BigDecimal add = new BigDecimal(s1).add(new BigDecimal(s2));
        String s = String.valueOf(add);
        System.out.println(s);

        ListNode dumpy = new ListNode(-1);
        ListNode curr = dumpy;

        for (int i = 0; i < s.length(); i++) {
            curr.next = new ListNode(Integer.valueOf(s.charAt(i) - '0'));
            curr = curr.next;
        }
        ListNode res = reverlist(dumpy.next);
        return res;
    }

    /**
     * 翻转链表
     *
     * @param head
     * @return
     */
    private ListNode reverlist(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode pre = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode future = curr.next;
            curr.next = pre;
            pre = curr;
            curr = future;
        }
        return pre;
    }

    private ListNode reverlistV2(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode pre = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode future = curr.next;
            curr.next = pre;
            pre = curr;
            curr = future;
        }
        return pre;
    }

    @Test
    public void test() {
        ListNode s1 = new ListNode(7);
        ListNode s2 = new ListNode(8);
        ListNode s3 = new ListNode(0);

        s1.next = s2;
        s2.next = s3;

        ListNode n1 = new ListNode(9);
        ListNode n2 = new ListNode(6);
        ListNode n3 = new ListNode(5);
        n1.next = n2;
        n2.next = n3;

        ListNode listNode = addTwoNumbers(s1, n1);
        while (listNode != null) {
            System.out.print(listNode.val + " ");
            listNode = listNode.next;
        }

    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
